package so.shanku.essential.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import cn.jpush.android.api.JPushInterface;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/8/31.
 */
public class RegisterActivity extends BaseUIActivity {
    /**
     * 注册
     */
    @ViewInject(id = R.id.user_register_bt, click = "register_bt_click")
    private TextView user_register_bt;
    /**
     * 输入账号
     */
    @ViewInject(id = R.id.user_account_ed)
    private EditText user_account_ed;
    /**
     * 请输入验证码
     */
    @ViewInject(id = R.id.user_code_ed)
    private EditText user_code_ed;
    /**
     * 请输入邮箱
     */
    @ViewInject(id = R.id.user_email_ed)
    private EditText user_email_ed;
    /**
     * 请输入密码
     */
    @ViewInject(id = R.id.user_pwd_ed)
    private EditText user_pwd_ed;

    /**
     * 注册协议
     */
    @ViewInject(id = R.id.agree_tv, click = "agreement_click")
    private TextView agree_tv;

    /**
     * 发送验证码
     */
    @ViewInject(id = R.id.btn_send_code, click = "send_code_click")
    private TextView btn_send_code;
    private String registerName;
    private String code;  //验证码
    private TimeCount time; //定时器
    private String passWord;
    private String email;//邮箱

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);
        addUnderLine(agree_tv);
        setCenter_title(R.string.register);

        setBtn_menuText(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        sendCodeClick();
        time = new TimeCount(120000, 1000);
    }

    /**
     * 获取验证码（防止网络延时发送多条验证码）
     */
    public void sendCodeClick() {
        btn_send_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (judgeMobileNo()) {
                    getData_UserSendCode();
                }
            }
        });
    }

    /**
     * 注册协议
     *
     * @param view
     */
    public void agreement_click(View view) {
        jumpTo(UrlWebviewActivity.class);
    }


    /**
     * 调用发送验证码接口
     */
    private void getData_UserSendCode() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userPhone", registerName);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_RegisterGetCode);
        queue.setWhat(GetDataConfing.What_RegisterGetCode);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }


    /**
     * 数据回调
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            loadingToast.dismiss();
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(RegisterActivity.this,
                        entity.getInfo())) {
                    if (entity.getWhat() == GetDataConfing.What_RegisterGetCode) {
                        time.start();
                        btn_send_code.setEnabled(false);
                    } else if (entity.getWhat() == GetDataConfing.what_CheckRegister) {
                        /**
                         * 注册信息保存
                         */
                        JsonMap<String, Object> data = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        Utils.saveUserInfos(RegisterActivity.this, data);
                        toast.showToast(R.string.regisger_success);

                        setResult(RESULT_OK);
                        finish();

                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }

        }
    };

    /**
     * 判断手机号码
     */

    public boolean judgeMobileNo() {
        registerName = user_account_ed.getText().toString();
        if (TextUtils.isEmpty(registerName)) {
            //手机号码为空的情况
            toast.showToast(R.string.register_name_null);
            return false;
        } else if (!StringUtil.isMobileNO(registerName)) {
            toast.showToast(R.string.phone_formal_error);
            return false;
        }
        return true;
    }

    //验证码倒计时
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            //参数依次为总时长,和计时的时间间隔
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            btn_send_code.setText(getString(R.string.revalidation));
            code = "";
            btn_send_code.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btn_send_code.setText(millisUntilFinished / 1000 + getString(R.string.second));
        }
    }

    public void register_bt_click(View view) {
        if (registerJudge()) {
            getData_UserSubmitCode();
        }
    }

    /**
     * 注册提交
     */
    private void getData_UserSubmitCode() {

        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", registerName);
        params.put("userPhone", registerName);
        params.put("pwd", passWord);
        params.put("email", email);
        params.put("code", code);
        params.put("tag", JPushInterface.getRegistrationID(this));
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_CheckRegister);
        queue.setWhat(GetDataConfing.what_CheckRegister);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }


    /**
     * 注册的判断
     */

    public boolean registerJudge() {
        code = user_code_ed.getText().toString();
        passWord = user_pwd_ed.getText().toString();
        email = user_email_ed.getText().toString();
        if (!judgeMobileNo()) {
            return false;
        }
        if (TextUtils.isEmpty(code)) {
            toast.showToast(R.string.pls_input_code);
            return false;
        }
        if (TextUtils.isEmpty(passWord)) {
            toast.showToast(R.string.register_password_null);
            return false;
        } else {
            if (!isPasswordAuthentication(passWord)) {
                return false;
            }
        }
        if (TextUtils.isEmpty(email)) {
//			toast.showToast(R.string.email_cannot_empty);
//			isemail = false;
            return true;
        } else {
            if (!StringUtil.isEmail(email)) {
                toast.showToast(R.string.email_style_error);
                return false;
            } else {
                return true;
            }
        }

    }

    /**
     * 密码判断
     */
    public boolean isPasswordAuthentication(String password) {
        if (!StringUtil.passwordAuthenticationLength(password)) {
            toast.showToast(R.string.register_passwordRule);
            return false;
        } else if (!StringUtil.passwordAuthentication(password)) {
            toast.showToast(R.string.password_format_error);
            return false;
        }
        return true;
    }
}
